import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import { SAVE } from './abc'
import { getuserInfo } from '@/api/login'
import { getQiniuToken, uploadQiniu } from "@/api/api";

export default new Vuex.Store({
  state: {
    // a:1,
    uid: '',
    token: '',
    userInfo: {},
    isLogin: false,
    publish_num:0,
    liked_num:0
  },
  //计算属性
  getters: {
  },
  // 改变数据
  mutations: {
    // changea(state,val){
    //   state.a = val
    // }
    [SAVE](state, [key, val]) {
      state[key] = val
    },
    clear(state) {
      state['uid'] = ''
      state['token'] = ''
      state['userInfo'] = {}
      state['isLogin'] = false
      state['liked_num'] =0 
      state['publish_num'] =0 
    }
  },
  actions: {
    //调接口
    getuserInfo({ commit }, token) {
    return   getuserInfo({
        token
      }).then(res => {
        console.log(res)
        let { uid, userInfo,liked_num,publish_num} = res;

        commit('save', ['uid', uid])
        commit('save', ['userInfo', userInfo])
        commit('save', ['token', token])
        commit('save', ['isLogin', true])
        commit('save',['liked_num',liked_num])
        commit('save',['publish_num',publish_num])
      })
    },
    //上传图片
    async upload(o, fileList) {
      //接受fileList
      if (!Array.isArray(fileList) || fileList.length === 0) {
        return []; //上传到服务器的图片路径
      }
      console.log(fileList)
      let task = fileList.map((v) => {
        return new Promise((resolve, reject) => {
          let file = v.file; //二进制 文件
          let { type } = file; //jpg png
          //  拿到类型  比如jpg
          type = type.split("/")[1];
          // 重新命名 
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;

          getQiniuToken().then(({ token }) => {
            // token   是靠  我们的用户名密码 等认证信息生成的
            console.log(token);
            const formdata = new FormData();
            formdata.append("file", file);
            formdata.append("token", token);
            formdata.append("key", file_name);

            uploadQiniu(formdata).then((res) => {
              resolve(`http://toutiao.longxiaokj.com/` + res.key);
            });
          });
        });
      });
      // await Promise.all(task).then(res => {
      //   console.log(res)
      // })
      // console.log(task)
      let imgList = await Promise.all(task);

      return imgList;
      //  @return []  上传到服务器的图片路径
    },
  },
  //模块化
  modules: {
  }
})
